<template>
  <div class="card card-flush shadow-lg">
    <div class="card-header pt-7">
      <h3 class="card-title align-items-start flex-column">
        <span class="card-label fw-bold text-gray-800">最近一个月提交Top{{ selectedLimit }}</span>
        <span class="fw-semibold fs-6 mt-1 text-gray-500">按提交行数排序</span>
      </h3>
      <div class="card-toolbar">
        <div class="input-group input-group-sm">
          <select
            v-model="selectedLimit"
            aria-label="选择限制"
            class="form-select form-select-sm"
            @change="fetchData"
          >
            <option value="5">前5名</option>
            <option value="10">前10名</option>
            <option value="all">所有</option>
          </select>
          <button class="btn btn-sm btn-primary" @click="fetchData">刷新</button>
        </div>
      </div>
    </div>
    <div class="card-body pt-6">
      <div v-if="loading" class="text-center">
        <div class="spinner-border" role="status">
          <span class="sr-only">加载中...</span>
        </div>
      </div>
      <div v-else-if="error" class="alert alert-danger">
        {{ error }}
      </div>
      <div v-else class="table-responsive h-425px h-lg-425px">
        <table
          class="table-row-dashed gs-0 gy-3 sticky-header sticky-footer my-0 table align-middle"
        >
          <thead>
            <tr class="fs-6 fw-bold border-bottom-0 text-gray-800">
              <th class="min-w-20px p-0 pb-3 text-center">序号</th>
              <th class="min-w-100px p-0 pb-3 text-start">姓名</th>
              <th
                class="min-w-80px sortable cursor-pointer p-0 pb-3 text-end"
                @click="sortBy('commit_count')"
              >
                提交次数
                <span v-if="sortKey === 'commit_count'">
                  <i :class="`bi bi-arrow-${sortDirection === 'asc' ? 'up' : 'down'}`"></i>
                </span>
              </th>
              <th
                class="min-w-80px sortable cursor-pointer p-0 pb-3 text-end"
                @click="sortBy('total_changes')"
              >
                总变化行
                <span v-if="sortKey === 'total_changes'">
                  <i :class="`bi bi-arrow-${sortDirection === 'asc' ? 'up' : 'down'}`"></i>
                </span>
              </th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, i) in topData" :key="i">
              <td class="fw-bold text-center">{{ i + 1 }}</td>
              <td>
                <span class="fw-bold fs-3 text-gray-800">{{ item.name }}</span>
                <KTIcon
                  :icon-name="roleSettings[item.role].icon"
                  :icon-class="`fs-5 text-${roleSettings[item.role].color} ms-2`"
                />
                <span :class="`badge badge-light-${roleSettings[item.role].color} ms-1`">{{
                  roleSettings[item.role].name
                }}</span>
                <br />
                <span class="fw-semibold fs-8 text-gray-500">
                  {{ item.department ? item.department.substring(10) : '' }}
                </span>
              </td>
              <td class="fw-bold text-end">{{ item.commitCount }}</td>
              <td class="fw-bold text-end">{{ item.totalChanges }}</td>
            </tr>
          </tbody>
          <tfoot>
            <tr class="fs-6 fw-bold text-gray-800">
              <th>{{ selectedLimit === 'all' ? '总计' : `前${selectedLimit}名总计` }}</th>
              <th class="text-end">{{ totals.totalCommits }}</th>
              <th class="text-end">{{ totals.totalChanges }}</th>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { engineerService } from '@/services/business/engineer.service';
import { roleSettings } from '@/utils/roleUtils';
import type { TopCommitter } from '@/types/business/engineer';
import KTIcon from '@/core/helpers/kt-icon/KTIcon.vue';

const topData = ref<TopCommitter[]>([]);
const loading = ref(true);
const error = ref<string | null>(null);
const selectedLimit = ref('5');

const sortKey = ref('total_changes');
const sortDirection = ref('desc');

const sortBy = (key: string) => {
  if (sortKey.value === key) {
    sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc';
  } else {
    sortKey.value = key;
    sortDirection.value = 'desc';
  }
  fetchData();
};

const fetchData = async () => {
  try {
    loading.value = true;
    error.value = null;
    topData.value = await engineerService.getLastMonthTopCommitters(
      selectedLimit.value,
      sortKey.value,
      sortDirection.value,
    );
  } catch (err) {
    console.error('Failed to fetch top last month:', err);
    error.value = '加载最近一个月Top5失败，请稍后重试';
  } finally {
    loading.value = false;
  }
};

const totals = computed(() => {
  if (topData.value.length === 0) return { totalCommits: 0, totalChanges: 0 };

  const sumCommits = topData.value.reduce((sum, item) => sum + item.commitCount, 0);
  const sumChanges = topData.value.reduce((sum, item) => sum + item.totalChanges, 0);

  return {
    totalCommits: sumCommits,
    totalChanges: sumChanges,
  };
});

onMounted(fetchData);
</script>
